﻿using Dapper;
using JX.Core;
using JX.Core.Entity;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JX.Application
{
	/// <summary>
	/// 提现管理服务接口
	/// </summary>
	public class MentionServiceAppDapper : IMentionServiceAppDapper
	{
		private readonly IMentionLogRepositoryDapper _MentionLogRepository;
		private readonly IUsersServiceAppDapper _UsersService;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="MentionLogRepository"></param>
		/// <param name="UsersService"></param>
		public MentionServiceAppDapper(IMentionLogRepositoryDapper MentionLogRepository, IUsersServiceAppDapper UsersService)
		{
			_MentionLogRepository = MentionLogRepository;
			_UsersService = UsersService;
		}

		/// <summary>
		/// 申请提现。成功Data属性返回MentionLogID，失败返回错误原因。
		/// </summary>
		/// <param name="mentionLogEntity">提现数据</param>
		/// <param name="PayPassword">支付密码</param>
		/// <returns></returns>
		public ResultInfo MentionApply(MentionLogEntity mentionLogEntity, string PayPassword)
		{
			var resultInfo = MentionInitValidate(mentionLogEntity, PayPassword);
			if(resultInfo.Status==0)
				return resultInfo;

			//计算手续费用
			decimal HandlingCharge = CalculatMentionHandlingCharge(mentionLogEntity.ApplicationAmount.GetValueOrDefault());

			//记录提现日志
			mentionLogEntity.ApplicationTime = DateTime.Now;
			mentionLogEntity.HandlingCharge = HandlingCharge;
			mentionLogEntity.Remark = (string.IsNullOrEmpty(mentionLogEntity.Remark)) ? "申请提现" : "申请提现###" + mentionLogEntity.Remark;
			mentionLogEntity.MentionStatus = 0;
			mentionLogEntity.Operator = "";
			mentionLogEntity.OperatingTime = new DateTime?();
			mentionLogEntity.LogTime = DateTime.Now;
			mentionLogEntity.MentionNO = DataSecurity.MakeFileRndName();
			mentionLogEntity.Memo = "";
			int MentionLogID = _MentionLogRepository.Insert(mentionLogEntity);
			if (MentionLogID <= 0)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "申请提现失败";
				return resultInfo;
			}
			else
			{
				resultInfo.Status = 1;
				resultInfo.Msg = "提现申请已提交";
				resultInfo.Data = MentionLogID.ToString();
				return resultInfo;
			}
		}
		/// <summary>
		/// 申请提现。成功Data属性返回MentionLogID，失败返回错误原因。
		/// </summary>
		/// <param name="mentionLogEntity">提现数据</param>
		/// <param name="PayPassword">支付密码</param>
		/// <returns></returns>
		public async Task<ResultInfo> MentionApplyAsync(MentionLogEntity mentionLogEntity, string PayPassword)
		{
			var resultInfo = MentionInitValidate(mentionLogEntity, PayPassword);
			if (resultInfo.Status == 0)
				return resultInfo;

			//计算手续费用
			decimal HandlingCharge = CalculatMentionHandlingCharge(mentionLogEntity.ApplicationAmount.GetValueOrDefault());

			//记录提现日志
			mentionLogEntity.ApplicationTime = DateTime.Now;
			mentionLogEntity.HandlingCharge = HandlingCharge;
			mentionLogEntity.Remark = (string.IsNullOrEmpty(mentionLogEntity.Remark)) ? "申请提现" : "申请提现###" + mentionLogEntity.Remark;
			mentionLogEntity.MentionStatus = 0;
			mentionLogEntity.Operator = "";
			mentionLogEntity.OperatingTime = new DateTime?();
			mentionLogEntity.LogTime = DateTime.Now;
			mentionLogEntity.MentionNO = DataSecurity.MakeFileRndName();
			mentionLogEntity.Memo = "";
			int MentionLogID = await _MentionLogRepository.InsertAsync(mentionLogEntity);
			if (MentionLogID <= 0)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "申请提现失败";
				return resultInfo;
			}
			else
			{
				resultInfo.Status = 1;
				resultInfo.Msg = "提现申请已提交";
				resultInfo.Data = MentionLogID.ToString();
				return resultInfo;
			}
		}

		/// <summary>
		/// 人工提现。成功则扣除会员资金余额；失败则修改提现状态，并记录失败原因。
		/// </summary>
		/// <param name="MentionLogID">提现记录ID</param>
		/// <param name="MentionStatus">提现状态：1：提现成功；2：提现失败；3：处理中；</param>
		/// <returns></returns>
		public ResultInfo MentionByArtificial(int MentionLogID, int MentionStatus = 1)
		{
			#region 数据验证
			var mentionLogEntity = _MentionLogRepository.Get(MentionLogID);
			var resultInfo = MentionValidate(mentionLogEntity);
			if (resultInfo.Status==0)
			{
				return resultInfo;
			}
			#endregion
			mentionLogEntity.Operator = string.IsNullOrEmpty(MyHttpContext.CurrentUserName) ? "System" : MyHttpContext.CurrentUserName;
			mentionLogEntity.OperatingTime = DateTime.Now;
			mentionLogEntity.MentionStatus = MentionStatus;
			if (MentionStatus == 1)
			{
				mentionLogEntity.Remark += "<br/>审核通过！申请金额已经发放！";
			}
			if (_MentionLogRepository.Update(mentionLogEntity))
			{
				if (MentionStatus == 1)
				{
					//扣除会员的资金余额
					string memo = "提现成功！提现金额："+ mentionLogEntity.ApplicationAmount.ToString() + "；手续费："+ mentionLogEntity.HandlingCharge.ToString();
					_UsersService.UserEncourageStrategy(0,"Minus",2, mentionLogEntity.Applicant, mentionLogEntity.ApplicationAmount.ToDecimal(), memo, memo);
				}
				resultInfo.Status = 1;
				resultInfo.Msg = "操作成功";
			}
			else
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "更新提现状态失败";
			}
			return resultInfo;
		}
		/// <summary>
		/// 人工提现。成功则扣除会员资金余额；失败则修改提现状态，并记录失败原因。
		/// </summary>
		/// <param name="MentionLogID">提现记录ID</param>
		/// <param name="MentionStatus">提现状态：1：提现成功；2：提现失败；3：处理中；</param>
		/// <returns></returns>
		public async Task<ResultInfo> MentionByArtificialAsync(int MentionLogID, int MentionStatus = 1)
		{
			#region 数据验证
			var mentionLogEntity = _MentionLogRepository.Get(MentionLogID);
			var resultInfo = MentionValidate(mentionLogEntity);
			if (resultInfo.Status == 0)
			{
				return resultInfo;
			}
			#endregion
			mentionLogEntity.Operator = string.IsNullOrEmpty(MyHttpContext.CurrentUserName) ? "System" : MyHttpContext.CurrentUserName;
			mentionLogEntity.OperatingTime = DateTime.Now;
			mentionLogEntity.MentionStatus = MentionStatus;
			if (MentionStatus == 1)
			{
				mentionLogEntity.Remark += "<br/>审核通过！申请金额已经发放！";
			}
			var bFlag = await _MentionLogRepository.UpdateAsync(mentionLogEntity);
			if (bFlag)
			{
				if (MentionStatus == 1)
				{
					//扣除会员的资金余额
					string memo = "提现成功！提现金额：" + mentionLogEntity.ApplicationAmount.ToString() + "；手续费：" + mentionLogEntity.HandlingCharge.ToString();
					_UsersService.UserEncourageStrategy(0, "Minus", 2, mentionLogEntity.Applicant, mentionLogEntity.ApplicationAmount.ToDecimal(), memo, memo);
				}
				resultInfo.Status = 1;
				resultInfo.Msg = "操作成功";
			}
			else
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "更新提现状态失败";
			}
			return resultInfo;
		}

		/// <summary>
		/// 计算提现手续费用
		/// </summary>
		/// <param name="MentionAmount">提现金额</param>
		/// <returns></returns>
		public decimal CalculatMentionHandlingCharge(decimal MentionAmount)
		{
			var config = ConfigHelper.Get<UserConfig>();
			decimal HandlingCharge = DataConverter.CDecimal(config.MentionFeeBegin);
			if (MentionAmount > config.MentionMoneyBegin1)
			{
				HandlingCharge = decimal.Round(MentionAmount * DataConverter.CDecimal(config.MentionFeeBegin1) / 100, 2);
			}
			return HandlingCharge;
		}
		/// <summary>
		/// 用于在提现之前，验证提现记录数据的完整性。失败返回错误原因，并把当前提现记录状态修改成“提现失败”。
		/// </summary>
		/// <param name="mentionLogEntity"></param>
		/// <returns></returns>
		public ResultInfo MentionValidate(MentionLogEntity mentionLogEntity)
		{
			ResultInfo resultInfo = new ResultInfo();
			if (mentionLogEntity == null)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现记录不存在";
				return resultInfo;
			}
			if (mentionLogEntity.MentionStatus != 0)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "此提现记录已经处理过，不能重复处理！";
				return resultInfo;
			}

			var config = ConfigHelper.Get<UserConfig>();
			string errMsg = "";
			string UserName = mentionLogEntity.Applicant;
			decimal vAmount = mentionLogEntity.ApplicationAmount.ToDecimal();
			decimal HandlingCharge = mentionLogEntity.HandlingCharge.ToDecimal();
			decimal trueAmount = vAmount - HandlingCharge;
			if (vAmount <= 0)
			{ 
				errMsg = "###提现金额不能为0";
			}
			if (string.IsNullOrEmpty(UserName))
			{ 
				errMsg = "###提现会员没有找到"; 
			}
			if (string.IsNullOrEmpty(mentionLogEntity.MentionNO))
			{ 
				errMsg = "###提现编号不能为空"; 
			}
			if (string.IsNullOrEmpty(mentionLogEntity.BankAccount))
			{
				errMsg = "###提现账户不能为空";
			}
			if (string.IsNullOrEmpty(mentionLogEntity.BankName))
			{
				errMsg = "###银行名称不能为空";
			}
			if (string.IsNullOrEmpty(mentionLogEntity.Cardholder))
			{
				errMsg = "###持卡人姓名不能为空";
			}
			if (vAmount < config.MentionMoneyBegin)
			{
				errMsg = "###最小提现金额为" + config.MentionMoneyBegin.ToString() + "元";
			}
			if (trueAmount <= 0)
			{
				errMsg = "###提现金额在扣除手续费后，不能小于0";
			}
			var usersByUserName = _UsersService.GetByUserName(mentionLogEntity.Applicant);
			if (usersByUserName == null)
			{
				errMsg = "###提现会员没有找到";
			}
			if (vAmount > usersByUserName.Balance)
			{
				errMsg = "###提现金额不能大于资金余额";
			}
			if (!string.IsNullOrEmpty(errMsg))
			{
				mentionLogEntity.Operator = string.IsNullOrEmpty(MyHttpContext.CurrentUserName) ? "System" : MyHttpContext.CurrentUserName;
				mentionLogEntity.OperatingTime = DateTime.Now;
				mentionLogEntity.MentionStatus = 2;
				mentionLogEntity.Remark += errMsg;
				_MentionLogRepository.Update(mentionLogEntity);
				resultInfo.Status = 0;
				resultInfo.Msg = errMsg;
			}
			else
			{
				resultInfo.Status = 1;
			}
			return resultInfo;
		}

		/// <summary>
		/// 用于申请提现时的数据验证
		/// </summary>
		/// <param name="mentionLogEntity"></param>
		/// <param name="PayPassword"></param>
		/// <returns></returns>
		private ResultInfo MentionInitValidate(MentionLogEntity mentionLogEntity, string PayPassword)
		{
			#region 数据验证
			ResultInfo resultInfo = new ResultInfo();
			if (mentionLogEntity == null)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现记录不存在";
				return resultInfo;
			}
			if (mentionLogEntity.ApplicationAmount <= 0)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现金额不能为0";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(mentionLogEntity.Applicant))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现会员没有找到";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(mentionLogEntity.BankAccount))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现账号不能为空";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(mentionLogEntity.BankName))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "银行名称不能为空";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(mentionLogEntity.Cardholder))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "持卡人姓名不能为空";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(PayPassword))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "支付密码不能为空";
				return resultInfo;
			}
			var config = ConfigHelper.Get<UserConfig>();
			if (!config.IsMention)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "不允许提现";
				return resultInfo;
			}
			if (mentionLogEntity.ApplicationAmount < config.MentionMoneyBegin)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "最小提现金额为" + config.MentionMoneyBegin.ToString() + "元";
				return resultInfo;
			}
			var usersByUserName = _UsersService.GetByUserName(mentionLogEntity.Applicant);
			if (usersByUserName == null)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现会员没有找到";
				return resultInfo;
			}
			if (mentionLogEntity.ApplicationAmount > usersByUserName.Balance)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "提现金额不能大于资金余额";
				return resultInfo;
			}
			if (StringHelper.MD5(PayPassword) != usersByUserName.PayPassword)
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "支付密码不对，无法提现！";
				return resultInfo;
			}
			if (_MentionLogRepository.IsExist(" and Applicant='" + mentionLogEntity.Applicant + "' and MentionStatus in (0,3) "))
			{
				resultInfo.Status = 0;
				resultInfo.Msg = "同一账号已经存在提现申请，不能重复提交！";
				return resultInfo;
			}
			resultInfo.Status = 1;
			resultInfo.Msg = string.Empty;
			return resultInfo;
			#endregion
		}
	}
}
